/*
 	This file is part of ExportGnuCash.

    ExportGnuCash is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ExportGnuCash is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ExportGnuCash.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.sourceforge.gnucash.outputformat;

import java.io.IOException;
import java.io.Writer;

import javax.swing.filechooser.FileFilter;

import net.sourceforge.gnucash.model.Account;
import net.sourceforge.gnucash.model.GnuCashBook;
import net.sourceforge.gnucash.model.Split;
import net.sourceforge.gnucash.model.Transaction;

public class CSVOutputFormat implements OutputFormat {

	@Override
	public void export(GnuCashBook book, Writer writer) throws IOException {
		for (Account  acc : book.accounts.values()) {
			writer.write(acc.getFullName());
			writer.write(";;;;;;;;\n");
            for (Transaction t : acc.trans) {
            	writer.write(";");
            	writer.write(notNull(t.dateDue));
				writer.write(";");
				writer.write(notNull(t.datePosted));
				writer.write(";");
				writer.write(notNull(t.description));
				writer.write(";");
				writer.write(notNull(t.transactionType));
				writer.write(";");
				Split split = t.getSplit(acc.guid);
				if (split != null){
					writer.write(""+split.amount);
					writer.write(";");
					writer.write(notNull(split.action));
					writer.write(";");
					writer.write(notNull(split.memo));
				}
				else
					writer.write(";;");
				Split splitOther = null;
				writer.write(";");
				if (!t.isSplit()) {
					splitOther = t.getOtherSplit(acc.guid);
					writer.write(getAccountFullName(book, splitOther));
				} else
					writer.write("multisplit");

				writer.write("\n");
			};
        }
	}

	@Override
	public FileFilter getFileFilter() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private static String getAccountFullName(GnuCashBook book, Split splitOther) {
		if (splitOther == null)
			return "";
		Account acc = book.getAccountByUUID(splitOther.accountGuid);
		if (acc == null)
			return "";
		return acc.getFullName();
	}

	private static String notNull(String str) {
    	if (str == null) return "";
		return str;
	}


}
